package com.xzz.cloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xzz.cloud.alibaba.service.PaymentService;
import com.xzz.cloud.entity.CommonResult;
import com.xzz.cloud.entity.Payment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: hhz
 * @createDate: 2021-4-6
 */
@RestController
public class OrderController {
    @Resource
    private PaymentService paymentService;

    @RequestMapping("/consumer/payment/{id}")
    @SentinelResource(value = "paymentSQL", fallback = "handlerFallback", blockHandler = "blockHandler")
    public CommonResult<Payment> payment(@PathVariable Long id){
        CommonResult<Payment> result = paymentService.payment(id);
        if(id == 4){
            throw  new IllegalArgumentException("IllegalArgumentException,非法参数异常.....");
        }else if(result.getData()==null){
            throw new NullPointerException("NullPointerException,该Id没有对应记录.空指针异常.....");
        }
        return  result;
    }
    //本例是fallback的兜底
    public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "兜底异常类handlerFallback,Exception内容: " + e.getMessage(), payment);
    }

    //本例是blockHandler的兜底
    public CommonResult blockHandler(@PathVariable Long id, BlockException e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水,BlockException: " + e.getMessage(), payment);
    }
}
